package com.csun.cmny.provider.service.impl;

import com.alibaba.fastjson.JSON;
import com.csun.cmny.base.dto.LoginAuthDto;
import com.csun.cmny.base.enums.ErrorCodeEnum;
import com.csun.cmny.provider.dto.ActivityQueryDto;
import com.csun.cmny.provider.dto.OldmanQueryDto;
import com.csun.cmny.provider.exceptions.OmcBizException;
import com.csun.cmny.provider.model.domain.*;
import com.csun.cmny.provider.model.dto.WelfareIntroduceDto;
import com.csun.cmny.provider.model.dto.WelfareMessageDto;
import com.csun.cmny.provider.model.exceptions.UacBizException;
import com.csun.cmny.provider.model.vo.CareTypeCountVo;
import com.csun.cmny.provider.model.vo.DeviceCountVo;
import com.csun.cmny.provider.model.vo.QueryMachineOldInfoVo;
import com.csun.cmny.provider.model.vo.ReportFormCountVo;
import com.csun.cmny.provider.service.*;
import com.csun.cmny.provider.utils.JuheWeatherUtil;
import com.csun.cmny.util.RedisKeyUtil;
import com.csun.cmny.util.UrlUtil;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
@Transactional
public class OmcQueryMachineServiceImpl implements OmcQueryMachineService {

    @Resource
    private OmcWelfareMessageService omcWelfareMessageService;
    @Resource
    private OmcWelfareIntroduceService omcWelfareIntroduceService;
    @Resource
    private DmcRpcService dmcRpcService;
    @Resource
    private CacRpcService cacRpcService;
    @Resource
    private OldmanService oldmanService;
    @Resource
    private OmcWelfareActivityService omcWelfareActivityService;
    @Resource
    private OmcWelfareActivityCarouselService omcWelfareActivityCarouselService;
    @Resource
    private OmcCycleExpenseItemService omcCycleExpenseItemService;
    @Resource
    private RedisTemplate<String, Object> redisTemplate;

//    private static String todayDate;
//
//    private static JSONObject weatherJson;

    @Override
    public ReportFormCountVo reportFormCount(LoginAuthDto loginAuthDto) {

        Long groupId = loginAuthDto.getGroupId();
        ReportFormCountVo vo = new ReportFormCountVo();

        //查询设备统计
        List<DeviceCountVo> deviceCountVos = dmcRpcService.queryDeviceNumByGroupByDeviceType(groupId);

        //查询院内老人id
        List<Integer> oldmanIdList = oldmanService.queryInOldmanIdList(groupId);

        //按自理类型查询老人
        List<CareTypeCountVo> careTypeCountVos = cacRpcService.queryOldmanNumGroupByCareType(oldmanIdList);

        //查询老人统计信息
        Map<String,Object> oldmanCountData = oldmanService.oldmanCount(groupId);
        vo.setCareTypeCountVos(careTypeCountVos);
        vo.setDeviceCountVos(deviceCountVos);
        vo.setOldmanCountData(oldmanCountData);

        return vo;
    }

    @Override
    public Integer saveIntroduce(WelfareIntroduceDto welfareIntroduceDto, LoginAuthDto loginAuthDto) {

        if(welfareIntroduceDto.getIntroduce().length()>4990){
            throw new UacBizException(ErrorCodeEnum.DMC100615003);
        }
        //福利院介绍
        OmcWelfareIntroduce wiQuery = new OmcWelfareIntroduce();
        wiQuery.setIntroduceType(welfareIntroduceDto.getIntroduceType());
        wiQuery.setGroupId(loginAuthDto.getGroupId());
        wiQuery = omcWelfareIntroduceService.selectOne(wiQuery);

        OmcWelfareIntroduce welfareIntroduce = new OmcWelfareIntroduce();

        //如果没有该类型介绍，则新增
        if(wiQuery == null){

            //拷贝属性
            BeanUtils.copyProperties(welfareIntroduceDto,welfareIntroduce);

            //设置首图片
            if(welfareIntroduce.getIntroduce() != null){
                if(welfareIntroduce.getIntroduce().equals("")){
                    welfareIntroduce.setFirstPic("");
                }else{
                    List<String> urls = UrlUtil.extractImg(welfareIntroduce.getIntroduce());
                    if(urls.size() > 0){
                        welfareIntroduce.setFirstPic(urls.get(0));
                    }else{
                        welfareIntroduce.setFirstPic("");
                    }
                }
            }
            welfareIntroduce.setUpdateInfo(loginAuthDto);
            welfareIntroduce.setGroupId(loginAuthDto.getGroupId());

            return omcWelfareIntroduceService.save(welfareIntroduce);
        }else {
            wiQuery.setUpdateInfo(loginAuthDto);
            wiQuery.setIntroduce(welfareIntroduceDto.getIntroduce());
            wiQuery.setRemark(welfareIntroduceDto.getRemark());
            //设置首图片
            if(welfareIntroduceDto.getIntroduce() != null){
                if(welfareIntroduceDto.getIntroduce().equals("")){
                    wiQuery.setFirstPic("");
                }else{
                    List<String> urls = UrlUtil.extractImg(welfareIntroduceDto.getIntroduce());
                    if(urls.size() > 0){
                        wiQuery.setFirstPic(urls.get(0));
                    }else{
                        wiQuery.setFirstPic("");
                    }
                }
            }
            return omcWelfareIntroduceService.updateById(wiQuery);
        }
    }

    @Override
    public List<OmcWelfareIntroduce> getIntroduceByIntroduceType(Integer type, LoginAuthDto loginAuthDto) {

        OmcWelfareIntroduce wiQuery = new OmcWelfareIntroduce();
        wiQuery.setGroupId(loginAuthDto.getGroupId());
        if(type <= 4 && type > 0){
            wiQuery.setIntroduceType(type);
        }
        return omcWelfareIntroduceService.select(wiQuery);
    }

    @Override
    public Integer saveMessage(WelfareMessageDto welfareMessageDto, LoginAuthDto loginAuthDto) {

        if(welfareMessageDto.getMessage().length() > 65535 ||  welfareMessageDto.getRemark().length() > 65535) {
            throw new UacBizException(ErrorCodeEnum.DMC100615003);
        }

        OmcWelfareMessage wmQuery = new OmcWelfareMessage();
        wmQuery.setGroupId(loginAuthDto.getGroupId());
        List<OmcWelfareMessage> wmList = omcWelfareMessageService.select(wmQuery);
        if(wmList.size() <1){
            BeanUtils.copyProperties(welfareMessageDto,wmQuery);
            wmQuery.setUpdateInfo(loginAuthDto);
            wmQuery.setGroupId(loginAuthDto.getGroupId());
            return omcWelfareMessageService.save(wmQuery);
        }else {
            wmQuery = wmList.get(0);
//            if(welfareMessageDto.getMessage() != null && !welfareMessageDto.getMessage().equals("")){
                wmQuery.setMessage(welfareMessageDto.getMessage());
//            }
//            if(welfareMessageDto.getRemark() != null && !welfareMessageDto.getRemark().equals("")){
                wmQuery.setRemark(welfareMessageDto.getRemark());
//            }
            return omcWelfareMessageService.updateById(wmQuery);
        }
    }

    @Override
    public List<OmcWelfareMessage> getMessage(LoginAuthDto loginAuthDto) {

        OmcWelfareMessage wmQuery = new OmcWelfareMessage();
        wmQuery.setGroupId(loginAuthDto.getGroupId());
        List<OmcWelfareMessage> wmList = omcWelfareMessageService.select(wmQuery);

        return wmList;
    }

    @Override
    public Integer saveWelfareActivity(OmcWelfareActivity welfareActivity, LoginAuthDto loginAuthDto) {

        if(welfareActivity.getActivity().length()>4990){
            throw new UacBizException(ErrorCodeEnum.DMC100615003);
        }
        //同名校验
        checkActivityNameRepeat(welfareActivity);

        welfareActivity.setUpdateInfo(loginAuthDto);
        welfareActivity.setGroupId(loginAuthDto.getGroupId());

        //设置首图片
        if(welfareActivity.getActivity() != null){
            if(welfareActivity.getActivity().equals("")){
                welfareActivity.setFirstPic("");
            }else{
                List<String> urls = UrlUtil.extractImg(welfareActivity.getActivity());
                if(urls.size() > 0){
                    welfareActivity.setFirstPic(urls.get(0));
                }else{
                    welfareActivity.setFirstPic("");
                }
            }
        }
        if(welfareActivity.isNew()){

            return omcWelfareActivityService.save(welfareActivity);
        }else {
            return omcWelfareActivityService.updateById(welfareActivity);
        }
    }

    @Override
    public Integer deleteByActivityId(Long activityId) {
        return omcWelfareActivityService.deleteByKey(activityId);
    }

    @Override
    public PageInfo queryActivitiesWithPage(ActivityQueryDto activityQueryDto, LoginAuthDto loginAuthDto) {

       return omcWelfareActivityService.queryActivitiesWithPage(activityQueryDto,loginAuthDto);
    }

//    @Override
//    public int addActivityCarousel(Long picId, LoginAuthDto loginAuthDto) {
//
//        //测试轮播图id是否重复
//        checkCarouselRepeat(picId,loginAuthDto);
//
//        OmcWelfareActivityCarousel wac = new OmcWelfareActivityCarousel();
//        wac.setPicId(picId);
//        wac.setGroupId(loginAuthDto.getGroupId());
//        wac.setUpdateInfo(loginAuthDto);
//        return omcWelfareActivityCarouselService.save(wac);
//    }

    @Override
    public int deleteCarouselById(Long carouselId, LoginAuthDto loginAuthDto) {
        return omcWelfareActivityCarouselService.deleteByKey(carouselId);
    }

    @Override
    public OmcWelfareActivityCarousel queryCarouselList(LoginAuthDto loginAuthDto) {
        OmcWelfareActivityCarousel wacQuery = new OmcWelfareActivityCarousel();
        wacQuery.setGroupId(loginAuthDto.getGroupId());
        OmcWelfareActivityCarousel wac = omcWelfareActivityCarouselService.selectOne(wacQuery);
        return wac;
    }

    @Override
    public String getTodayWeather() {
//        Date date = new Date();
//        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
//
//        if(todayDate == null || todayDate.equals("")){
//            todayDate = dateFormat.format(date);
//            weatherJson = JuheWeatherUtil.getWeather();
//            return weatherJson;
//        }else{
//            String nowdate = dateFormat.format(date);
//            if(!nowdate.equals(todayDate) || weatherJson == null || weatherJson.equals("")){
//                weatherJson = JuheWeatherUtil.getWeather();
//                return weatherJson;
//            }else {
//                return weatherJson;
//            }
//        }

        //获取今日日期组成redis key
        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String todayDate = dateFormat.format(date);
        //判断是否缓存了今日天气
        if(!redisTemplate.hasKey(RedisKeyUtil.getOmcQueryMachineWeather(todayDate))){
            String weatherJson = JuheWeatherUtil.getWeather();
            redisTemplate.opsForValue().set(RedisKeyUtil.getOmcQueryMachineWeather(todayDate), weatherJson,24, TimeUnit.HOURS);
            return weatherJson;
        }else {
            String s = (String) redisTemplate.opsForValue().get(RedisKeyUtil.getOmcQueryMachineWeather(todayDate));
            return s;
        }
    }

    @Override
    public QueryMachineOldInfoVo getOldmanInfoByOldmanId(Long oldmanId, LoginAuthDto loginAuthDto) {
        return oldmanService.getOldmanInfoByOldmanId(oldmanId,loginAuthDto);
    }

    @Override
    public PageInfo queryOldmanList(OldmanQueryDto oldmanQueryDto, LoginAuthDto loginAuthDto) {
        return oldmanService.queryOldmanList(oldmanQueryDto,loginAuthDto);
    }

    @Override
    public List<OmcCycleExpenseItem> getOldmanCycleItem(Long oldmanId, LoginAuthDto loginAuthDto) {
        OmcCycleExpenseItem itemQuery = new OmcCycleExpenseItem();
        itemQuery.setOldmanId(oldmanId);
        return omcCycleExpenseItemService.select(itemQuery);
    }

    @Override
    public int saveActivityCarousel(String picString, LoginAuthDto loginAuthDto) {
        return omcWelfareActivityCarouselService.saveActivityCarousel(picString,loginAuthDto);
    }

    @Override
    public List<OmcWelfareIntroduce> getIntroduceByGroupId(Integer type, Long groupId) {
        OmcWelfareIntroduce wiQuery = new OmcWelfareIntroduce();
        wiQuery.setGroupId(groupId);
        if(type <= 4 && type > 0){
            wiQuery.setIntroduceType(type);
        }
        return omcWelfareIntroduceService.select(wiQuery);
    }

    public void checkCarouselRepeat(Long picId,LoginAuthDto loginAuthDto){
        Example example = new Example(OmcWelfareActivityCarousel.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("picId",picId);
        int ret = omcWelfareActivityCarouselService.selectCountByExample(example);
        if(ret > 0){
            throw new OmcBizException(ErrorCodeEnum.OMC10050001);
        }
    }

    //校验活动名称重复
    public void checkActivityNameRepeat(OmcWelfareActivity welfareActivity){
        Example example = new Example(OmcWelfareActivity.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("activityName",welfareActivity.getActivityName());
        criteria.andEqualTo("activityType",2);
        if(welfareActivity.getId() != null && welfareActivity.getId() != 0){
            criteria.andEqualTo("id",welfareActivity.getId());
        }
        int ret = omcWelfareActivityService.selectCountByExample(example);
        if(ret > 1){
            throw new OmcBizException(ErrorCodeEnum.OMC10050002);
        }
    }
}
